//
//  RCComposeController.swift
//  RC-微博0305
//
//  Created by 任淳 on 16/3/16.
//  Copyright © 2016年 ReverChun. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

let screenWidth:CGFloat = UIScreen.mainScreen().bounds.width
let screenHeight:CGFloat = UIScreen.mainScreen().bounds.height
let inSetMargin:CGFloat = 8

class RCComposeController: UIViewController,UITextViewDelegate {

    //选择图片
    func selectPicture() {
    
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.chooseVC.view.snp_updateConstraints { (make) -> Void in
                make.height.equalTo(screenHeight / 3 * 2)
                
            }
            
        }
        //立即刷新
        view.layoutIfNeeded()
        
    }
    
    //选择表情
    func selectEmoticon() {
        
        
    }
    
    //返回按钮的方法
    func toBack() {
        
        textView.resignFirstResponder()
        //返回上一个控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //发送微博按钮
    func send() {
        //只有文字的时候
        var string = "https://api.weibo.com/2/statuses/update.json"
        
        let manager = AFHTTPSessionManager()
        
        guard let token = RCUserModel.sharedUserModel.access_token else {
            
            SVProgressHUD.showErrorWithStatus("token过期了")
            return
        }
        
        let parameters = ["access_token":token,"status":textView.text]
        
        
        //判断  是否发布图片
        if chooseVC.imageArray.count != 0 {
            
            string = "https://upload.api.weibo.com/2/statuses/upload.json"
            //发送图片的请求方法

            manager.POST(string, parameters: parameters
                , constructingBodyWithBlock: { (formData) -> Void in
                               
                    //把图片拼到formdata中
                    /*
                    1.data: 标示要上传文件的二进制数据
                    2.name: 服务器接收的字段名称 pic
                    3.fileName: 服务器存储的名称 可以随便传,新浪微博为了防止图片名称重复 会自己命名
                    4.mimeType: 上传的文件格式  图片的格式 一般是 image/jpeg,
                    : 表示忽略文件格式
                    */
                    
                    //把图片转换成二进制数据
                    let imageData = UIImagePNGRepresentation(self.chooseVC.imageArray.first!)
                    
                    formData.appendPartWithFileData(imageData!, name: "pic", fileName: "hahaha", mimeType: "application/octet-stream")
                    
                }, progress: nil, success: { (_, result) -> Void in
                     SVProgressHUD.showSuccessWithStatus("发布成功了")
                }, failure: { (_, error) -> Void in
                     SVProgressHUD.showErrorWithStatus("发送失败")
            })
            
            
        }else {
            //只发表文字的时候
            manager.POST(string, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                //成功
                SVProgressHUD.showSuccessWithStatus("发布成功了")
                }) { (_, error) -> Void in
                    //失败
                    SVProgressHUD.showErrorWithStatus("发送失败")
            }
            
        }
        
        //不管是否成功 都返回首页 dismiss掉
        toBack()
        
    }
    
    //键盘改变的方法
    func keyboardChanged(n:NSNotification) {
        
        print("========\(n)")
        //获取键盘收回所需的时间
        let duration = (n.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        //获取键盘的Frame
        let rect = (n.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        let translateY = rect.origin.y - screenHeight
        
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.toolBar.transform = CGAffineTransformMakeTranslation(0,translateY)
            
//            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
//                make.bottom.equalTo(translateY)
//                
//            })
            
//            self.view.layoutIfNeeded()
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        view.backgroundColor = UIColor.whiteColor()
        
        //自定义导航栏
        setNav()
        
        setToolBar()
        //添加textView
        setTextView()
        
        //添加底部工具条
        
        //添加选择图片控制器
        setChoosePic()
        
        view.bringSubviewToFront(toolBar)
        
        //监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    //图片一出现就弹出键盘
    override func viewDidAppear(animated: Bool) {
        textView.becomeFirstResponder()
        
    }
    
    //添加选择图片控制器
    func setChoosePic() {
        //控制器里 添加控制器 的步骤
        addChildViewController(chooseVC)
        view.addSubview(chooseVC.view)
        
            self.chooseVC.view.snp_makeConstraints { (make) -> Void in
                make.left.right.bottom.equalTo(self.view)
                make.height.equalTo(0)
            
        }
        
        
    }
    
    
    //添加底部工具条
    func setToolBar() {
        view.addSubview(toolBar)

        
        toolBar.backgroundColor = UIColor.darkGrayColor()
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(44)
        }
        
        var items = [UIBarButtonItem]()
        
        //添加 UIBarButtonItem类型的对象到数据源数组中
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
            let imageName = item["imageName"]
            let btn = UIFactory.btnWithImage(nil, imageName: imageName)
            if let actionName = item["actionName"] {
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            let barItem = UIBarButtonItem(customView: btn)
            //添加到数组中
            items.append(barItem)
            
            //添加弹簧类型的item  FlexibleSpace: 可伸缩的弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
            
        }
        
        items.removeLast()
        
        toolBar.items = items

        
    }
    
    func setTextView() {
        
        view.addSubview(textView)
        
        textView.addSubview(placeholder)
        
        placeholder.snp_makeConstraints { (make) -> Void in
            make.left.top.equalTo(textView).offset(inSetMargin)
            make.right.equalTo(textView).offset(-inSetMargin)
            make.height.equalTo(21)
        }
        
    }
    
    
    func setNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "toBack")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = myView
        myView.addSubview(titleLab)
        myView.addSubview(nameLab)
    
        titleLab.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(myView)
            make.centerX.equalTo(myView)
        }
    
        nameLab.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(myView)
            make.centerX.equalTo(myView)
        }
        
    }
    
    //textview的代理方法 textview里面文字改变时调用
    func textViewDidChange(textView: UITextView) {
       
        //有文字就隐藏placeholder
        placeholder.hidden = textView.hasText()
        //有文字就让发送按钮可以点击  创建后默认是默认不可点击的
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }

    //懒加载
    //titleView
     lazy var myView:UIView = {
        
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        return myView
    }()
    
    lazy var titleLab:UILabel = UIFactory.labelWith("发送", textColor: UIColor.blackColor(), fontSize: 17 ,alignment: NSTextAlignment.Center)

    
    lazy var nameLab:UILabel = UIFactory.labelWith(RCUserModel.sharedUserModel.name ?? "", textColor: UIColor.orangeColor(), fontSize: 14 ,alignment: NSTextAlignment.Center)
    //textView
    lazy var textView:UITextView = {
        let textView:UITextView = UITextView(frame: CGRect(x: 0, y: 0, width: screenWidth, height:screenHeight / 3))
        textView.backgroundColor = UIColor.greenColor()
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.blackColor()

        textView.delegate = self
        //新的隐藏键盘的发式
        textView.keyboardDismissMode = .OnDrag
        //设置键盘垂直方向可以拽动 设置可以滑动出边界
        textView.alwaysBounceVertical = true
        return textView
    }()
    
    //占位文字placeholder
    lazy var placeholder:UILabel = {
//       let lab = UILabel(frame: CGRect(x: 0, y: 0, width: screenWidth , height: 21))
        let lab = UILabel()
        lab.text = "分享新鲜事……"
        lab.textColor = UIColor.darkGrayColor()
        lab.font = UIFont.systemFontOfSize(18)
        return lab
    }()
    
    //底部工具条
    lazy var toolBar:UIToolbar = UIToolbar()
    
    //图片选择控制器
    lazy var chooseVC:RCChoosePictureController = RCChoosePictureController()
    
    //隐藏键盘的方式
//    func scrollViewDidScroll(scrollView: UIScrollView) {
//        
//        view.endEditing(true)
//        //让底部工具条回到初始位置
//        UIView.animateWithDuration(0.25) { () -> Void in
//
//            self.toolBar.transform = CGAffineTransformIdentity
//
//        }
//    }

    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}

